package me.magicall.db.sql.where;

import java.util.BitSet;

import me.magicall.db.sql.FollowingElements;
import me.magicall.db.sql.condition.ConditionsOperator;
import me.magicall.db.sql.condition.OneCondition;

/*
 * FIXME:sql包太蛋疼,虽然结构严谨,但是真正使用的话将要写更多的代码.
 * 同时,in具有Function的特点,但又不具备作为Expression出现在select子句中;
 * 具有ConditionOperator的特点,但又因sql部分有一个右括号在参数之后,不具备一般ConditionOperator与OneCondition的组合关系,只能写成继承关系
 * 故决定废弃此种实现.
 */
/**
 * where子句
 * 
 * @author MaGiCalL
 */
public class Where extends FollowingElements<OneCondition> {

	private final BitSet conditionUsingOr = new BitSet();
	private int curBitIndex = 0;

	public Where() {
		super();
	}

	public Where(final OneCondition firstElement) {
		super(firstElement);
	}

	/**
	 * 增加一个条件,使用and与其他条件连接.效果同add方法
	 * 
	 * @param expression
	 */
	public void addCondition(final OneCondition expression) {
		add(expression);
	}

	/**
	 * 增加一个条件,使用指定的连接符与其他条件连接
	 * 
	 * @param expression
	 * @param operator
	 */
	public void addCondition(final OneCondition expression, final ConditionsOperator operator) {
		if (operator == ConditionsOperator.OR) {
			addConditionUsingOr(expression);
		} else {
			add(expression);
		}
	}

	/**
	 * 增加一个条件,使用or与其他条件连接
	 * 
	 * @param expression
	 */
	public void addConditionUsingOr(final OneCondition expression) {
		add(expression);
		conditionUsingOr.set(curBitIndex);
		++curBitIndex;
	}

	@Override
	protected String elementConnector(final OneCondition curElement, final int index) {
		//bitSet默认为false
		return conditionUsingOr.get(index) ? ConditionsOperator.OR.toSql() : ConditionsOperator.AND.toSql();
	}

	@Override
	public StringBuilder appendTo(final StringBuilder sb) {
		final OneCondition firstElement = getFirstElement();
		if (firstElement == null) {
			return sb;
		}
		sb.append(" ").append(getPrefix());
		firstElement.appendTo(sb);
		int index = 0;
		for (final OneCondition condition : getOtherElements()) {
			sb.append(elementConnector(condition, index));
			condition.appendTo(sb);
			++index;
		}
		return sb;
	}
}
